<template>
  <el-form label-width="100px">
    <el-form-item label="SPU名称">
      <el-input
        placeholder="请你输入SPU名称"
        v-model="SpuParams.spuName"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU品牌">
      <el-select v-model="SpuParams.tmId">
        <el-option
          v-for="(item, index) in allTradeMark"
          :key="item.id"
          :label="item.tmName"
          :value="item.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input
        type="textarea"
        placeholder="请你输入SPU描述"
        v-model="SpuParams.description"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU图片">
      <!-- v-model:fileList->展示默认图片 
                 action:上传图片的接口地址
                 list-type:文件列表的类型
            -->
      <el-upload
        v-model:file-list="imgList"
        action="/api/admin/product/fileUpload"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :before-upload="handlerUpload"
      >
        <el-icon>
          <Plus />
        </el-icon>
      </el-upload>
      <el-dialog v-model="dialogVisible">
        <img
          w-full
          :src="dialogImageUrl"
          alt="Preview Image"
          style="width: 100%; height: 100%"
        />
      </el-dialog>
    </el-form-item>
    <el-form-item label="SPU销售属性">
      <!-- 展示销售属性的下拉菜单 -->
      <el-select :placeholder="unSelectSaleAttr.length?`还可选择${unSelectSaleAttr.length}个`:'无'" v-model="saleAttrIdAndValueName" value-key="baseSaleAttrId">
        <el-option
          v-for="(item, index) in unSelectSaleAttr"
          :key="item.id"
          :label="item.name"
          :value="{baseSaleAttrId:item.id,saleAttrName:item.name}"
        ></el-option>
      </el-select>
      <el-button
        @click="addSaleAttr"
        :disabled="!saleAttrIdAndValueName.saleAttrName"
        style="margin-left: 10px"
        type="primary"
        size="default"
        icon="Plus"
        >添加属性</el-button
      >
      <!-- table展示销售属性与属性值的地方 -->
      <el-table border style="margin: 10px 0px" :data="saleAttr">
        <el-table-column
          label="序号"
          type="index"
          align="center"
          width="80px"
        ></el-table-column>
        <el-table-column
          label="销售属性名字"
          width="120px"
          prop="saleAttrName"
        ></el-table-column>
        <el-table-column label="销售属性值">
          <!-- row:即为当前SPU已有的销售属性对象 -->
          <template #="{ row, $index }">
            <el-tag
              style="margin: 0px 5px"
              @close="row.spuSaleAttrValueList.splice(index, 1)"
              v-for="(item, index) in row.spuSaleAttrValueList"
              :key="item.id"
              class="mx-1"
              closable
            >
              {{ item.saleAttrValueName }}
            </el-tag>
            <el-input
              v-if="row.flag"
              @blur="toLook(row)"
              :ref="(vc:any) =>inputArr[$index] = vc"
              placeholder="请你输入属性值"
              v-model="row.saleAttrValue"
              size="small"
              style="width: 100px"
            ></el-input>
            <el-button
              v-else
              @click="toEdit(row,$index)"
              type="primary"
              size="small"
              icon="Plus"
            ></el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120px">
          <template #="{ row, $index }">
            <el-button
              type="primary"
              size="small"
              icon="Delete"
              @click="saleAttr.splice($index, 1)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="default" @click="save">保存</el-button>
      <el-button type="primary" size="default" @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ref, computed,nextTick} from "vue";
import type { UploadProps } from "element-plus";
import { ElMessage } from "element-plus";
import {
  reqAllTradeMark,
  reqSpuImageList,
  reqSpuHasSaleAttr,
  reqAllSaleAttr,
  reqAddOrUpdateSpu
} from "@/api/product/spu/index.ts";
import type {
  SpuData,
  AllTradeMark,
  SpuHasImg,
  SaleAttrResponseData,
  HasSaleAttrResponseData,
  Trademark,
  SpuImg,
  SaleAttr,
  HasSaleAttr,
  SaleAttrValue
} from "@/api/product/spu/type";
const inputArr = ref<any>([])
const saleAttrIdAndValueName = ref<any>({})
const dialogImageUrl = ref("");
let dialogVisible = ref<boolean>(false);
//存储已有的SPU这些数据
let allTradeMark = ref<Trademark[]>([]);
//商品图片
let imgList = ref<SpuImg[]>([]);
//已有的SPU销售属性
let saleAttr = ref<SaleAttr[]>([]);
//全部销售属性
let allSaleAttr = ref<HasSaleAttr[]>([]);
//存储已有的SPU对象
let SpuParams = ref<SpuData>({
  category3Id: "", //收集三级分类的ID
  spuName: "", //SPU的名字
  description: "", //SPU的描述
  tmId: "", //品牌的ID
  spuImageList: [],
  spuSaleAttrList: [],
});
let $emit = defineEmits(["changeSence"]);
//点击取消按钮:通知父组件切换场景为0,展示有的SPU的数据
const cancel = () => {
  $emit("changeSence", {flag:0,type:'update'});
};
const initHasSpuData = async (data: SpuData) => {
  SpuParams.value = data;
  let result: AllTradeMark = await reqAllTradeMark();
  allTradeMark.value = result.data;
  let result2: SpuHasImg = await reqSpuImageList(data.id as number);
  imgList.value = result2.data.map((item) => {
    return {
      name: item.imgName,
      url: item.imgUrl,
    };
  });
  let result3: SaleAttrResponseData = await reqSpuHasSaleAttr(
    data.id as number
  );
  saleAttr.value = result3.data;
  let result4: HasSaleAttrResponseData = await reqAllSaleAttr();
  allSaleAttr.value = result4.data;
};
  //过滤出来未选的属性
  let unSelectSaleAttr = computed(() => {
    let unSaleAttr = allSaleAttr.value.filter((item) => {
      return saleAttr.value.every((item2) => {
        return item2.saleAttrName != item.name;
      });
    });
    return unSaleAttr;
  });
// 照片预览
const handlePictureCardPreview: UploadProps["onPreview"] = (
  uploadFile: any
) => {
  dialogImageUrl.value = uploadFile.imgUrl;
  dialogVisible.value = true;
};
//照片钱上传成功之前的钩子约束文件的大小与类型
const handlerUpload = (file: any) => {
  if (
    file.type == "image/png" ||
    file.type == "image/jpeg" ||
    file.type == "image/gif"
  ) {
    if (file.size / 1024 / 1024 < 3) {
      return true;
    } else {
      ElMessage({
        type: "error",
        message: "上传文件务必小于3M",
      });
      return false;
    }
  } else {
    ElMessage({
      type: "error",
      message: "上传文件务必PNG|JPG|GIF",
    });
    return false;
  }
};
const toLook = (row: SaleAttr) => {
  row.flag = false;
  let newSaleAttrValue:SaleAttrValue = {
    baseSaleAttrId:row.baseSaleAttrId,
    saleAttrValueName:(row.saleAttrValue as string)
  }
  if((row.saleAttrValue as string).trim()==''){
    ElMessage({
        type:'error',
        message:'销售属性值不能为空'
    })
    return
  }
  let result = row.spuSaleAttrValueList.find(item=>{
    return item.saleAttrValueName == row.saleAttrValue
  })
  if(result){
  return ElMessage({
        type:'error',
        message:'销售属性值不能重复'
    })
  }
  row.spuSaleAttrValueList.push(newSaleAttrValue)
};
// 点击添加销售属性值
const toEdit = (row: SaleAttr,$index: number) => {
  row.flag = true;
  row.saleAttrValue = ''
  nextTick(()=>{
    inputArr.value[$index].focus()
  })
};
// 添加属性
const addSaleAttr = ()=>{
    let newSaleAttr:SaleAttr = {
        baseSaleAttrId:saleAttrIdAndValueName.value.baseSaleAttrId,
        saleAttrName:saleAttrIdAndValueName.value.saleAttrName,
        spuSaleAttrValueList: []
    }
    // 将新数组追加到saleAttr
    saleAttr.value.push(newSaleAttr)
    //清空收集的数据
    saleAttrIdAndValueName.value = {}
}
// 保存 新增与修改
const save = async ()=>{
    SpuParams.value.spuImageList = imgList.value.map((item:any)=>{
        return {
            imgUrl:(item.response&&item.response.data) || item.url,
            imgName:item.name
        }
    })
    SpuParams.value.spuSaleAttrList = saleAttr.value
    let result = await reqAddOrUpdateSpu(SpuParams.value)
    if(result.code==200){
     ElMessage({
        type:'success',
        message:SpuParams.value.id?'修改成功':'新增成功'
    })
    $emit("changeSence", {flag:0,type:SpuParams.value.id?'update':'add'});
    }else{
        ElMessage({
        type:'success',
        message:SpuParams.value.id?'修改失败':'新增失败'
    })
    }
}
const initAddSpu = async (c3Id:number)=>{
    // 点击添加spu按钮时清空上次新增时填写的记录
    Object.assign(SpuParams.value,{
        category3Id: "", //收集三级分类的ID
        spuName: "", //SPU的名字
        description: "", //SPU的描述
        tmId: "", //品牌的ID
        id:"",
        spuImageList: [],
        spuSaleAttrList: [],
    })
    imgList.value=[]
    saleAttr.value = []
    saleAttrIdAndValueName.value = {}
    SpuParams.value.category3Id = c3Id
    let result: HasSaleAttrResponseData = await reqAllSaleAttr();
    allSaleAttr.value = result.data;
    let result2: AllTradeMark = await reqAllTradeMark();
    allTradeMark.value = result2.data;
}
// 对外暴露
defineExpose({ initHasSpuData,initAddSpu });
</script>

<style scoped></style>
